import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import Login from "../views/Login";
import Register from "../views/Register";
import Media from "../views/Media";
import Play from "../views/Play";

Vue.use(VueRouter);

// 跳转同一页面多次报错;
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  // 重定向
  {
    path: "/",
    redirect: "home",
  },
  // 登录页 /login
  {
    path: "/login",
    name: "登录 -- Yukinoshita",
    component: Login,
  },
  // 注册页 /register
  {
    path: "/register",
    name: "注册 -- Yukinoshita",
    component: Register,
  },
  // 主页 /home
  {
    path: "/home",
    name: "主页 -- Yukinoshita",
    component: Home,
    meta: {
      login_required: true,
    },
  },
  // 番剧详情页 /media/:season
  {
    path: "/media/:season",
    name: "番剧详情 -- Yukinoshita",
    component: Media,
    meta: {
      login_required: true
    }
  },
  // 番剧播放页 /play/:season/:episode
  {
    path: "/play/:season/:episode",
    name: "播放番剧 -- Yukinoshita",
    component: Play,
    meta: {
      login_required: true,
    }
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach(function(to, from, next) {
  // 获取用户登录信息
  var logged_in = window.sessionStorage.getItem("User");
  // 解析成json对象
  var data = JSON.parse(logged_in);
  // 获取所取对象role属性
  // 获取目标路径
  var url = to.path;
  url = url.split("/");
  document.title = to.name;
  // 情况1. 页面无需登录
  // 情况2. 页面需登录 但未登录
  // 情况3. 页面需登录 且已登录登陆
  // 情况3.1 已登录 但身份不符
  // 情况3.2 已登录 且身份符合

  // 情况1
  if (to.meta.login_required == null) {
    next();
  } else {
    // 情况2
    if (!logged_in) {
      next('/login');
    }else {
      next();
    }
  }
});

export default router;
